package com.alibaba.citrus.cr.order.open.api.facade.service;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.order.open.api.facade.model.FulfillmentOrderData;
import com.alibaba.citrus.cr.order.open.api.facade.model.FulfillmentOrderMessage;
import com.alibaba.citrus.cr.order.open.api.facade.service.notifyquantity.FulfillmentNotifyQuantityHandler;
import com.alibaba.citrus.cr.order.open.api.facade.service.notifyquantity.FulfillmentNotifyQuantityHandlerManager;
import com.alibaba.citrus.cr.order.open.api.facade.transferorder.TransferOrderQueryService;
import com.alibaba.cloud.retail.delivery.api.model.delivery.enums.FulfillmentDirectionTypeEnum;
import com.alibaba.cloud.retail.delivery.api.model.delivery.enums.OrderTypeEnum;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crunifiedinventory.domain.allocateorder.dto.AllocateOrderLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateorder.model.AllocateOrder;
import com.epoch.app.crunifiedinventory.domain.allocateorder.service.AllocateOrderService;
import com.epoch.app.mninventorycenter.fulfillmentordermessageprocess.service.FulfillmentOrderMessageProcessService;
import com.epoch.app.mninventorycenter.model.dto.FulfillmentOrderMessageRequest;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author: yuhw
 * @date: 2024年03月01日 15:48
 **/
@Service
@Primary
public class FulfillmentOrderMessageProcessServiceImpl implements FulfillmentOrderMessageProcessService {
    private static Log log = Log.getLogger(FulfillmentOrderMessageProcessServiceImpl.class);

    @Resource
    private FulfillmentNotifyQuantityHandlerManager fulfillmentNotifyQuantityHandlerManager;
    @Resource
    private TransferOrderQueryService transferOrderQueryService;
    @Resource
    private AllocateOrderService allocateOrderService;
    private static final Set<String> acceptEventCodes = Sets.newHashSet("fulfillment_order_submit","fulfillment_order_close","fulfillment_order_cancel");

    @Override
    @FacadeInvoker
    public Result<String> notifyQuantity(FulfillmentOrderMessageRequest request) {
        log.info("FulfillmentOrderMessageProcessServiceImpl_request:{}", JSON.toJSONString(request));
        if (!accept(request)) {
            log.info("FulfillmentOrderMessageProcessServiceImpl_not_accept:{}",JSON.toJSONString(request));
            return Result.success("not_accept");
        }
        FulfillmentOrderMessage fulfillmentOrderMessage = JSON.parseObject(request.getMessage(),FulfillmentOrderMessage.class);
        FulfillmentOrderData data = fulfillmentOrderMessage.getData();
        //查询调拨单 TODO 考虑是否会出现sourceOrderNo不是调拨单号的正向履约单
//        TransferOrderQueryRequest transferOrderQueryRequest = new TransferOrderQueryRequest();
//        transferOrderQueryRequest.setTransferOrderCode(data.getSourceOrderNo());
//        Result<TransferOrder> transferOrderResult = transferOrderQueryService.query(transferOrderQueryRequest);
//        if (transferOrderResult == null || transferOrderResult.getResult() == null){
//            throw new FacadeException("OTS-03-005-00-15-230","查询调拨单" + data.getSourceOrderNo());
//        }
        //这里只用到了调拨单类型, 则直接查下数据库
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setCode(data.getSourceOrderNo());
        Result<List<AllocateOrder>> allocateOrderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        if (allocateOrderList == null || CollectionUtils.isEmpty(allocateOrderList.getResult())){
//            throw new FacadeException("OTS-03-005-00-15-230","查询调拨单" + data.getSourceOrderNo());
            return Result.fail("OTS-03-005-00-15-230", "查询调拨单" + data.getSourceOrderNo());
        }
        FulfillmentNotifyQuantityHandler fulfillmentNotifyQuantityHandler =
                fulfillmentNotifyQuantityHandlerManager.getFulfillmentNotifyQuantityHandler(allocateOrderList.getResult().get(0).getType().toString());
        fulfillmentNotifyQuantityHandler.handle(data);
        return Result.success(System.currentTimeMillis()+"");
    }

    private boolean accept(FulfillmentOrderMessageRequest request){
        if (request == null || StringUtil.isBlank(request.getMessage())){
            log.error("FulfillmentOrderMessageProcessServiceImpl_message_empty");
            return false;
        }
        FulfillmentOrderMessage fulfillmentOrderMessage = JSON.parseObject(request.getMessage(),FulfillmentOrderMessage.class);
        if (fulfillmentOrderMessage == null){
            log.error("FulfillmentOrderMessageProcessServiceImpl_message_empty");
            return false;
        }
        if (!acceptEventCodes.contains(fulfillmentOrderMessage.getEventCode())){
            log.error("FulfillmentOrderMessageProcessServiceImpl_message_event_not_match");
            return false;
        }
        FulfillmentOrderData data = fulfillmentOrderMessage.getData();
        return data != null && Arrays.asList(OrderTypeEnum.ALLOCATE_INBOUND,OrderTypeEnum.ALLOCATE_OUTBOUND,
                        OrderTypeEnum.ALLOCATE_RETURN_INBOUND,OrderTypeEnum.ALLOCATE_RETURN_OUTBOUND)
                .stream().anyMatch(orderTypeEnum -> orderTypeEnum.getValue().equals(data.getRefOrderType()))
                && FulfillmentDirectionTypeEnum.FORWARD.getValue().equals(data.getFulfillmentDirectionType())
                && StringUtils.isNoneBlank(data.getFulfillmentOrderNo(),data.getSourceOrderNo());
    }
}
